package com.hunray.rent.security;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.hunray.rent.entity.User;
import com.hunray.rent.service.IUserService;

public class UserRealm extends AuthorizingRealm {

	private IUserService userService;

	@Autowired
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String username = (String) principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authz = new SimpleAuthorizationInfo();
		User user = userService.findByUsername(username);
		authz.setRoles((Set<String>) user.getRoleNames());
		authz.setStringPermissions((Set<String>) user.getPermissionNames());
		return authz;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		User user = userService.findByUsername(username);
		if (user == null) {
			throw new UnknownAccountException();
		} else if (user.getLocked() == true) {
			throw new LockedAccountException();
		}
		SimpleAuthenticationInfo authc = new SimpleAuthenticationInfo(username,
				user.getPassword(), ByteSource.Util.bytes(user.getSalt()),
				getName());
		return authc;
	}

}
